var hid=getParameter("hid");
var region_id=getParameter("region_id");
var h_name="";
var region_name="";
var address="";
var house_imgs=null;//楼盘相册
var user=getUserEntityFromCache();
var attention_status=0;//关注状态
var flat_type_images = [];
var guider=0;
var from_backend=parseInt(getParameter("from_backend"));//后端来浏览

getSign();
$(function () {
    init();
    addEvent();
});

function init() {
    if(parseInt(user.role)==2){
        guider=localStorage.getItem("referee");
    }
    else {
        guider=user.uid;
    }

    if(isNaN(from_backend)){
        from_backend=0;
    }

    if(from_backend==1){
        getHouseDetail();
        getRecommendHouseList();
    }
    else {
        if (!user.isLogin()) {//没登录
            //微信授权回调回来
            if(code!=undefined&&code!=null&&code.length>0&&state=="pocket"){
                getUserInfo(function (data) {
                    user=new User(data.openid,data.mobile,data.nickname,data.headimgurl,data.uid,data.role,data.referee,data.parent_code,data.redpacket_money,data.redpacket_num,data.isgetredpacket);
                    user.cacheUserInfo(user.openid,user.nickname,user.mobile,user.avatar,user.uid,data.role,data.referee,data.parent_code,data.redpacket_money,data.redpacket_num,data.isgetredpacket);

                    getHouseDetail();
                    getRecommendHouseList();
                });
            }
            else {
                user.clearUserInfoCache();
                getUserAuthorize();
            }
        }
        else {
            getUserInfoOfApp(user.uid,function (data) {
                if(data!=undefined&&data!=null&&data.uid!=undefined&&data.uid!=null&&data.uid>0){
                    getHouseDetail();
                    getRecommendHouseList();
                }
            });
        }
    }
}

function addEvent() {
    $(".prev_img").click(function(){
        openPhotoSwipe();
    });

    $(".contact_logo").click(function(){
        window.location.href="/home";
    });

    $("#btn_contact").click(function(){
        if($(".online_selector").hasClass("slide")){
            hideChatBox();
        }
        else{
            showChatBox();
        }
    });

    $("#btn_report").click(function () {
        hideChatBox();
        showReportBox();
    });

    $("#btn_saveReport").click(function(){
        saveReport();
    });

    $("#btn_cancelReport").click(function(){
        hideReportBox();
    });

    $(".online_selector li").click(function(){
        var num = $(this).index();
        if(num==0){
            window.location.href="https://kefu.easemob.com/webim/im.html?configId=666a1310-a661-4c09-b9e3-8bc1c87764f3";
        }
        else{
            window.location.href="tel:021-62660590";
        }
        hideChatBox();
    });
    
    
    $("#btn_attention").click(function(){
        if(user.isLogin()&&user.uid!=null&&user.uid!=undefined&&user.uid!=""){
            if(attention_status==0){
                attention_status=1;
            }
            else {
                attention_status=0;
            }
            postHouseAttention();
        }
    });

    // $("#house_flat_list").on("click",".flat_img",function () {
    //     var url_str="";
    //     var url_arr = [];
    //     for(var i=0;i<$(".flat_img img").length;i++){
    //         url_arr.push($(".flat_img img").eq(i).attr("src"));
    //     }

    //     wx.previewImage({
    //         current: $(this).find("img").attr("src"), // 当前显示图片的http链接
    //         urls: url_arr // 需要预览的图片http链接列表
    //     });
    // });
    
    $(".house_info_primary li").eq(0).click(function () {// 地图模式
        if(h_name!=null&&h_name.length>0&&region_name!=null&&region_name.length>0){
            window.location.href="/house/map?hid="+hid+"&h_name="+escape(h_name)+"&region_name="+escape(region_name)+"&address="+escape(address);
        }
    });

    $(".house_info_primary li").eq(3).click(function () {
        var url="https://jr.fangdd.com/market/calculator?houseMoney="+$(this).attr("data-monney")+"&houseType=1&type=1&cityId=2475";//type贷款类型
        window.location.href=url;
    });

    $(".house_list").on("click",".house_item",function () {
        window.location.href="/house/detail?hid="+$(this).attr("data-id")+"&region_id="+$(this).attr("data-region");
    });

    $(".house_list").on("click",".house_return",function (e) {
        window.location.href="https://mp.weixin.qq.com/s?__biz=MzUxMDUwNDk5OQ==&mid=2247483738&idx=1&sn=8d42401efe80d71f1fa4ad928bfcd9c0&chksm=f900b812ce773104296101798aded368bb54da81d3761b36bd79355a24b13aae90cce77a9f86#rd";
        if ( e && e.stopPropagation ){
            e.stopPropagation(); 
        }
    });
}

var openPhotoSwipe = function() {
    var pswpElement = document.querySelectorAll('.pswp')[0];

    // build items array
    // var items = [
    //     {
    //         src: '../images/prev2.png',
    //         w: 496,
    //         h: 325,
    //         title: '小区图1',
    //     },
    //     {
    //         src: '../images/prev1.png',
    //         w: 496,
    //         h: 325,
    //         title: '小区图2',
    //
    //     },
    //     {
    //         src: '../images/prev3.png',
    //         w: 496,
    //         h: 325,
    //         title: '小区图3',
    //     }
    // ];

    // define options (if needed)
    var options = {
        // history & focus options are disabled on CodePen
        history: false,
        focus: false,

        showAnimationDuration: true,
        hideAnimationDuration: true

    };

    var gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, house_imgs, options);
    gallery.init();
};

//显示在线沟通
function showChatBox(){
    $(".online_selector").addClass("slide");
}

function hideChatBox(){
    $(".online_selector").removeClass("slide");
}

function typeimageclick(tid){
    console.log('tid='+tid);
    console.log(flat_type_images);
    if(tid >= flat_type_images.length){
        return;
    }
    var imgarr = flat_type_images[tid].typeimg;

    var arrays = [];
    for(var i=0;i<imgarr.length;i++){
        arrays.push('http://m.all-star.top'+imgarr[i].img_path);
    }

    console.log(arrays);
    
    wx.previewImage({
        current: arrays[0], // 当前显示图片的http链接
        urls: arrays // 需要预览的图片http链接列表
    });

    
}

//显示在线报备
function showReportBox(){
    var t=getComputedStyle(document.getElementById("report_box"),null).transitionDuration;
    $("#report_box").addClass("show");
    $(".mask").fadeIn(t);
}

function hideReportBox(){
    var t=getComputedStyle(document.getElementById("report_box"),null).transitionDuration;
    $("#report_box").removeClass("show");
    $(".mask").fadeOut(t,function () {
        resetReportFrom();
    });
}

//保存在线报备
function saveReport() {
    if(checkReportForm()){
        postReport();
    }
}

function resetReportFrom() {
    $("#contact").val("");
    $("#mobile").val("");
    $("#opt_report_type1").prop("checked","true");
    $("#opt_report_type2").prop("checked");
}

//检查在线报备表单
function checkReportForm() {
    var txt_contact=$("#contact").val().trim();
    var txt_mobile=$("#mobile").val().trim();

    $("#contact").parent().removeClass("has-error").removeClass("has-success");
    $("#mobile").parent().removeClass("has-error").removeClass("has-success");

    if(txt_contact.length<=0){
        $("#contact").parent().addClass("has-error");
        return false;
    }
    else if(txt_mobile.length<=0){
        $("#contact").parent().addClass("has-success");
        $("#mobile").parent().addClass("has-error");
        return false;
    }
    else if(!isValidMobile(txt_mobile)){
        $("#contact").parent().addClass("has-success");
        $("#mobile").parent().addClass("has-error");
        return false;
    }
    else {
        $("#contact").parent().addClass("has-success");
        $("#mobile").parent().addClass("has-success");
    }

    return true;
}

function postReport(){
    var txt_contact=$("#contact").val().toString().trim();
    var txt_mobile=$("#mobile").val().toString().trim();
    var opt_status=$("#report_type input[name='opt_report_type']:checked").val();


    $.ajax({
        type: "get",
        async: true,
        url: "/v1/report/add",
        data: {contacts:txt_contact,uid:user.uid,house_id:hid,phone:txt_mobile,referee:guider,status:opt_status},
        dataType: "json",
        beforeSend:function(){
            showLoading();
        },
        success: function(data){
            hideLoading();
            if(data.code=="success"){
                hideReportBox();
                showNotice("报备成功","success");
            }
            else {
                showNotice(data.message,"error");
            }
        },
        error: function(){
            hideLoading();
        }
    });
}

function getHouseDetail(){
    $.ajax({
        type: "get",
        async: true,
        url: "/v1/house/get",
        data: {id:hid,uid:user.uid},
        dataType: "json",
        beforeSend:function(){
            showLoading();
        },
        success: function(data){
            hideLoading();
            if(data.code=="success"){
                try {
                    var info=data.data.house;
                    if(info){
                        handlerHouseInfo(info);
                    }
                    else {
                        showAlert("信息不完整");
                    }
                }catch(e) {
                    showAlert("加载出错");
                }
            }
            else {
                showAlert(data.message);
            }
        },
        error: function(){
            hideLoading();
        }
    });
}

function handlerHouseInfo(data) {
    var house_unit_price="";
    var discount_str="优惠政策：";
    var payment_str="首付比例：";
    if(data){
        if(parseInt(data.has_attention.toString())==1){
            attention_status=1;
            $("#btn_attention").text("已关注").addClass("sel");
        }
        else {
            attention_status=0;
        }

        if(data.house_unit_price==null||data.house_unit_price==undefined||data.house_unit_price.length<=0||data.house_unit_price.toString()=="0"){
            house_unit_price="待定";
        }
        else {
            house_unit_price=data.house_unit_price;
        }

        h_name=data.house_name;
        region_name=data.region;
        address=data.address;
        $(".house_summary h2:first").text(data.house_name);
        $(".price_left b").text(house_unit_price);
        $(".return_price").text(data.return_money+"万/套");
        $(".house_info_primary span").eq(0).text(data.address);
        $(".house_info_primary span").eq(1).text(data.developer);
        $(".house_info_primary span").eq(2).text(data.property_company);

        if(parseInt(data.discount_1)>0){
            discount_str+="贷款:"+data.discount_1+"%&nbsp;&nbsp;";
        }
        if(parseInt(data.discount_2)>0){
            discount_str+="全款:"+data.discount_2+"%";
        }
        if(parseInt(data.discount_1)<=0&&parseInt(data.discount_2)<=0){
            discount_str+="--";
        }

        $(".house_info_primary span").eq(4).html(discount_str);

        $(".house_info_primary li").eq(3).attr("data-monney",data.total_price);
        if(parseInt(data.payment_rate)>0){
            $(".house_info_primary span").eq(3).text(payment_str+data.payment_rate+"%"+"（约"+parseInt(parseFloat(data.total_price)*parseInt(data.payment_rate)/100)+"万元）");
        }
        else {
            $(".house_info_primary span").eq(3).text("--");
        }

        $(".house_parameter span").eq(0).text(data.category);
        $(".house_parameter span").eq(1).text(data.property+"年");
        $(".house_parameter span").eq(3).text(data.building_type);
        $(".house_parameter span").eq(6).text(data.plot_ratio);
        $(".house_parameter span").eq(7).text(data.greening_rate+"%");
        $(".house_parameter span").eq(8).text(data.layout_number);
        $(".house_parameter span").eq(9).text(data.car_number);
        $(".house_parameter span").eq(10).text(data.decoration);



        if(parseInt(data.return_day)>0){
            $(".house_parameter span").eq(12).text(data.return_day+"天");
        }
        else {
            $(".house_parameter span").eq(12).text("--");
        }

        if(data.property_fee!=null&&data.property_fee!=undefined&&data.property_fee!="null"&&data.property_fee.toString().length>0){
            $(".house_parameter span").eq(11).text(data.property_fee+"元/平米/月");
        }
        else {
            $(".house_parameter span").eq(11).text("--");
        }

        if(data.checkout!=null&&data.checkout!=undefined&&data.checkout!="null"&&data.checkout.toString().length>0){
            $(".house_parameter span").eq(2).text(data.checkout);
        }
        else {
            $(".house_parameter span").eq(2).text("--");
        }


        if(data.floor_area!=null&&data.floor_area!=undefined&&data.floor_area!="null"&&data.floor_area.toString().length>0){
            $(".house_parameter span").eq(4).text(data.floor_area);//建筑面积
        }
        else {
            $(".house_parameter span").eq(4).text("--");//建筑面积
        }

        if(data.area_covered!=null&&data.area_covered!=undefined&&data.area_covered!="null"&&data.area_covered.toString().length>0){
            $(".house_parameter span").eq(5).text(data.area_covered);//占地面积
        }
        else {
            $(".house_parameter span").eq(5).text("--");//占地面积
        }

        //处理户型图
        var flat_images=data.houseTypeImage;
        flat_type_images=data.houseTypeImage;
        var flat_html="";
        if(flat_images!=null&&flat_images!=undefined&&flat_images.length>0){
            $(".house_flat_list").html("");
            var area_str="--";
            for(var i=0;i<flat_images.length;i++){
                if(!flat_images[i].area||flat_images[i].area.length<=0){
                    area_str="--";
                }
                else {
                    area_str=flat_images[i].area;
                }
                flat_html+=' <li class="clearfix">\n' +
                    '                    <div onclick="typeimageclick('+i+')" class="flat_img"><img src="'+m_domain+flat_images[i].img_path+'"></div>\n' +
                    '                    <div class="flat_des"><p><b>'+flat_images[i].name+'</b></p><p>'+flat_images[i].house_type+'&nbsp;&nbsp;'+area_str+'m²</p></div>\n' +
                    '                    <div class="flat_price"><p><span>'+flat_images[i].price+'</span>万起</p></div>\n' +
                    '                </li>';
            }

            $(".house_flat_list").html(flat_html);
        }
        else {
            $(".house_flat_list").html("<p>暂无户型信息</p>");
        }

        //处理小区图片
        var images=data.images;
        var images_strs="";

        if(images!=null&&images!=undefined&&images.length>0){
            $(".album_icon").show();
            $(".prev_img").attr("src", m_domain+images[0]);
            for(var i=0;i<images.length;i++){
                images_strs+='{"src": "'+m_domain+images[i]+'","w": 496,"h": 372,"title": "小区图'+(i+1)+'"},';
            }
            if(images_strs.length>0){
                images_strs=images_strs.substr(0,images_strs.length-1);
            }
            house_imgs=JSON.parse("["+images_strs+"]");
        }

        //处理楼盘动态
        var state_info=data.state_info;
        var state_info_html="";
        if(state_info!=null&&state_info!=undefined&&state_info.length>0){
            $(".house_info_list").html("");
            var info_content="";
            for(var i=0;i<state_info.length;i++){
                info_content=state_info[i]["content"];
                state_info_html+='<li><p>${info_content}</p></li>';
            }

            $(".house_info_list").html(state_info_html);
        }
        else {
            $(".house_info_list").html("<p>暂无动态信息</p>");
        }

    }
}


function getRecommendHouseList(){
    $.ajax({
        type: "get",
        async: true,
        url: "/v1/house/get-same-region-house",
        data: {'region_id':region_id},
        dataType: "json",
        beforeSend:function(){
            showLoading();
        },
        success: function(data){
            hideLoading();
            if(data.code=="success"){
                var data=data.data;
                appendHouseData(data);
            }
            else {
                showAlert(data.message);
            }
        },
        error: function(){
            hideLoading();
        }
    });
}

function appendHouseData(data) {
    var list;
    list = data.list;

    if (list != null && list.length > 0) {
        var house_html = "";
        var item;
        var house_room = "";
        var house_unit_price = "";
        var total_price = "";

        for (var i = 0; i < list.length; i++) {
            item = list[i];
            if (item.room2 == null || item.room2 == undefined || item.room2.length <= 0 || item.room2.toString() == "0") {
                house_room = item.room1;
            }
            else {
                house_room = item.room1 + "-" + item.room2;
            }

            if (item.house_unit_price == null || item.house_unit_price == undefined || item.house_unit_price.length <= 0 || item.house_unit_price.toString() == "0") {
                house_unit_price = "待定";
            }
            else {
                house_unit_price = item.house_unit_price + "元/㎡";
            }

            if (item.total_price == null || item.total_price == undefined || item.total_price.length <= 0 || item.total_price.toString() == "0") {
                total_price = "待定";
            }
            else {
                total_price = item.total_price + "万起";
            }

            var marks_html="";
            var w = window.screen.width;
            for(var index in item.marks){
                if((w<=320&&index<=3)||(w>320&&index<=4)){
                    marks_html+='<li>'+item.marks[index]+'</li>';
                }
            }

            house_html += ' <li class="house_item list-unstyled" data-id="' + item.id + '" data-region="'+item.region_id+'" >\n' +
                '            <div class="house_info" style="padding-bottom:'+(marks_html.length?14:0)+'px;">\n' +
                '                <div class="house_img"><img src="' + m_domain + item.img_path + '" class="img-responsive" onerror="this.src=\'/images/house_default.png\'" /></div>\n' +
                '                <div class="house_summary">\n' +
                '                    <p class="house_name">' + item.house_name + '</p>\n' +
                '                    <p class="house_area"><img src="/images/location_yellow.png" />&nbsp;&nbsp;&nbsp;&nbsp;' + item.parent_region + '&nbsp;&nbsp;' + item.region_name + '</p>\n' +
                '                    <p class="house_unit_price">单价：' + house_unit_price + '</p>\n' +
                '                    <p class="house_total_price">总价：' + total_price + '</p>\n' +
                '                    <ul class="house_marks">'+marks_html+'</ul>\n' +
                '                </div>\n' +
                '                <div class="house_return">\n' +
                '                    <div class="return_img"><img src="/images/logo_small.png" /></div>\n' +
                '                    <div class="return_des">\n' +
                '                        <p>口袋返现</p>\n' +
                '                        <p class="return_price">' + item.return_money + '万/套</p>\n' +
                '                    </div>\n' +
                '                    <div class="clearfix"></div>\n' +
                '                </div>\n' +
                '                <div class="clearfix"></div>\n' +
                '            </div>\n' +
                '            <div class="house_address">地址：' + item.address + '</div>\n' +
                '        </li>';
        }

        if (house_html != null && house_html.length > 0) {
            $(".house_list").eq(0).append(house_html);
        }
    }
    else {
        $(".house_list").eq(0).html("<p style='color:#ccc;padding-left: 15px;'>暂无推荐楼盘</p>");
    }
}

//关注、取消关注
function postHouseAttention(){
    $.ajax({
        type: "get",
        async: true,
        url: "/v1/favorite/edit",
        data: {uid:user.uid,house_id:hid,status:attention_status},
        dataType: "json",
        beforeSend:function(){
            showLoading();
        },
        success: function(data){
            hideLoading();
            if(data.code=="success"){
                try {
                    if(attention_status==1){//关注
                        $("#btn_attention").text("已关注").addClass("sel");
                        showNotice("关注成功","success");
                    }
                    else {
                        $("#btn_attention").text("+关注").removeClass("sel");
                        showNotice("已取消关注","success");
                    }
                }catch(e) {
                    if(attention_status==1) {//关注
                        showNotice("关注出错","error");
                    }
                    else {
                        showNotice("取消关注出错","error");
                    }
                }
            }
            else {
                showNotice(data.message,"error");
            }
        },
        error: function(){
            hideLoading();
        }
    });
}


function getSign(){
    $.ajax({
        type: "get",
        url: "/v1/wx-user/get-sign",
        data: {noncestr:noncestr, timestamp:timeStamp,url:window.location.href},
        dataType: "json",
        beforeSend:function(){

        },
        success: function(data){
            if(data.code=="success") {
                if (data.data != null && data.data.sign != null && data.data.sign != undefined) {
                    initWXConfig(data.data.sign);
                }
            }
            else {
                showAlert(data.err_msg);
            }
        },
        error: function(){
        }
    });
}



function initWXConfig(signature){
    wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: appId, // 必填，公众号的唯一标识，aa3ecfe3da55ba39e817d6f19f70725d
        timestamp: timeStamp, // 必填，生成签名的时间戳
        nonceStr: noncestr, // 必填，生成签名的随机串
        signature: signature,// 必填，签名，见附录1
        jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
    });

    wx.ready(function(){
        initWXShare();
        // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
    });

    wx.error(function(res){
        // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
    });

    wx.checkJsApi({
        jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
        success: function(res) {
            // 以键值对的形式返回，可用的api值true，不可用为false
            // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
        }
    });

}

function initWXShare() {
    var share_title="";
    var share_des="";
    var share_link="";
    var share_icon="";

    share_title=$(".house_name").eq(0).text()+" "+house_share_text;
    share_des="";
    share_link=window.location.href;
    share_icon="http://pocket.all-star.top/images/logo_small.jpg";

    wx.onMenuShareAppMessage({
        title: share_title, // 分享标题 $(".house_name").text()+"-"+
        desc: share_des, // 分享描述
        link: share_link,
        imgUrl: share_icon,
        type: '', // 分享类型,music、video或link，不填默认为link
        dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
        success: function () {
            // 用户确认分享后执行的回调函数
        },
        cancel: function () {
            // 用户取消分享后执行的回调函数
        }
    });

    wx.onMenuShareTimeline({
        title: share_title, // 分享标题
        link:share_link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: share_icon, // 分享图标
        success: function () {
            // 用户确认分享后执行的回调函数
        },
        cancel: function () {
            // 用户取消分享后执行的回调函数
        }
    });
}